package com.ccit.equip.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccit.common.exception.GymException;
import com.ccit.common.exception.fileUpload.FileEmptyException;
import com.ccit.common.result.Result;
import com.ccit.common.utils.RedisUtils;
import com.ccit.common.utils.UploadUtil;
import com.ccit.equip.service.impl.EquipServiceImpl;
import com.ccit.model.Equipment;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "器材管理")
@RestController
@RequestMapping("/equip")
public class EquipController {
    @Autowired
    private EquipServiceImpl equipService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UploadUtil uploadUtil;


    final String port = "8086";

    @ApiOperation(value = "获取所有器材名称")
    @GetMapping("/getAllEquipNames")
    public Result getAllEquipNames() {
        String key = "equipmentNames";
        boolean hasKey = redisUtils.hasKey(key);
        List<String> nameList;
        if (hasKey) {
            nameList = (List<String>)redisUtils.get(key);
        } else {
            QueryWrapper<Equipment> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("name");
            List<Equipment> list = equipService.list(queryWrapper);
            nameList = new ArrayList<>();
            for (Equipment equipment : list) {
                nameList.add(equipment.getName());
            }
        }

        if (nameList.size() > 0)
        {redisUtils.set(key, nameList);
            return Result.ok(nameList);
        }
        else
            throw new GymException(202, "数据请求失败");
    }

    @ApiOperation(value = "分页查询器材")
    @GetMapping("/getByPage/{current}/{size}")
    public Result listByPageEquip(@PathVariable Integer current,
                                  @PathVariable Integer size) {
        String key = "equipmentPage:" + current + ":" + size;
        boolean hasKey = redisUtils.hasKey(key);
        Page<Equipment> page;
        if (hasKey) {
            page = (Page<Equipment>)redisUtils.get(key);
        } else {
            Page<Equipment> equipmentPage = new Page<>(current, size);
            page = equipService.page(equipmentPage);
            redisUtils.set(key, page);
        }
        return Result.ok(page);
    }

    @ApiOperation(value = "修改器材")
    @PutMapping("/updateEquipment")
    public Result updateEquipment(@RequestParam(required = false) MultipartFile file, @RequestPart String equipStr) {
        //批量模糊删除所有包含keys的数据
        JSONObject object = JSON.parseObject(equipStr);
        Equipment equipment = equipService.getById(object.getLong("id"));

        equipment.setName(object.getString("name"));
        equipment.setCount(object.getInteger("count"));

        if (file != null) {
            String pathPrefix = new ApplicationHome(this.getClass()).getDir().getParentFile().getParentFile().getAbsolutePath();
            Map<String, String> map = new HashMap<>();
            map.put("pathPrefix", pathPrefix);
            map.put("src", "equipment");
            String fileName = uploadUtil.saveFile(file, map);
            equipment.setImgUrl("http://localhost:" + port + "/equipment/img/" + fileName);

            /*
            int lastIndexOf = equipment.getImgUrl().lastIndexOf("/");

            String img_path = equipment.getImgUrl().substring(lastIndexOf + 1, equipment.getImgUrl().length());
            System.out.println(img_path);

            String pathPrefix = new ApplicationHome(this.getClass()).getDir().getParentFile().getParentFile().getAbsolutePath();
            Map<String, String> map = new HashMap<>();
            map.put("pathPrefix", pathPrefix);
            map.put("src", "equipment");
            img_path=pathPrefix + "\\src\\main\\resources\\static\\"+ map.get("src") + "\\img\\"+img_path;

            File oldfile = new File(img_path);
            if (oldfile.exists()){
                if (oldfile.delete()){
                    String fileName = uploadUtil.saveFile(file, map);
                    equipment.setImgUrl("http://localhost:" + port + "/equipment/img/" + fileName);
                }else {
                    return Result.fail().message("删除失败");
                }
            }else {
                return Result.fail().message("文件不存在");
            }*/
        }

        boolean flag = equipService.updateById(equipment);
        if (flag) {
            redisUtils.deleteRedisKeys("equipmentNames");
            redisUtils.deleteRedisKeys("equipmentPage");
            return Result.ok();
        } else {
            return Result.fail().message("修改失败");
        }
    }

    @ApiOperation(value = "删除器材")
    @DeleteMapping("/deleteEquip/{id}")
    public Result removeEquipment(@PathVariable("id") Integer id) {
        //批量模糊删除所有包含keys的数据
        Equipment equipment = equipService.getById(id);
        int lastIndexOf = equipment.getImgUrl().lastIndexOf("/");
        String img_path = equipment.getImgUrl().substring(lastIndexOf + 1, equipment.getImgUrl().length());
        System.out.println(img_path);

        String pathPrefix = new ApplicationHome(this.getClass()).getDir().getParentFile().getParentFile().getAbsolutePath();
        Map<String, String> map = new HashMap<>();
        map.put("pathPrefix", pathPrefix);
        map.put("src", "equipment");
        img_path = pathPrefix + "\\src\\main\\resources\\static\\" + map.get("src") + "\\img\\" + img_path;

        File file = new File(img_path);

        boolean byId = equipService.removeById(id);
        if (byId) {
            redisUtils.deleteRedisKeys("equipment");
            if (file.exists()) {
                if (file.delete()) {
                    redisUtils.deleteRedisKeys("equipmentNames");
                    redisUtils.deleteRedisKeys("equipmentPage");
                    return Result.ok("删除成功");
                } else {
                    return Result.fail().message("删除失败");
                }
            } else {
                return Result.fail().message("文件不存在");
            }
        } else throw new GymException(202, "无此器材");

    }

    @ApiOperation(value = "批量删除器材")
    @DeleteMapping("/batchRemove")
    public Result batchRemoveEquipment(@RequestBody List<Long> idList) {
        //批量模糊删除所有包含keys的数据
        idList.forEach(id -> {
            Equipment equipment = equipService.getById(id);
            if (equipment == null) {
                throw new GymException(202, "无此器材" + id);
            } else {
                int lastIndexOf = equipment.getImgUrl().lastIndexOf("/");
                String img_path = equipment.getImgUrl().substring(lastIndexOf + 1, equipment.getImgUrl().length());
                System.out.println(img_path);

                String pathPrefix = new ApplicationHome(this.getClass()).getDir().getParentFile().getParentFile().getAbsolutePath();
                Map<String, String> map = new HashMap<>();
                map.put("pathPrefix", pathPrefix);
                map.put("src", "equipment");
                img_path = pathPrefix + "\\src\\main\\resources\\static\\" + map.get("src") + "\\img\\" + img_path;
                File file = new File(img_path);

                boolean byId = equipService.removeById(id);
                if (byId) {
                    redisUtils.deleteRedisKeys("equipment");
                    if (file.exists()) {
                        if (!file.delete()) {
                            throw new GymException(203, "删除图片失败");
                        }
                    }
                } else throw new GymException(203, "删除失败");
            }
        });
        redisUtils.deleteRedisKeys("equipmentNames");
        redisUtils.deleteRedisKeys("equipmentPage");
        return Result.ok("删除成功");
    }

    @ApiOperation(value = "保存器材")
    @PostMapping("/saveEquip")
    public Result uploadPicture(@RequestParam MultipartFile file, @RequestPart String equipStr) {
        if (file == null) {
            throw new FileEmptyException();
        }
        String pathPrefix = new ApplicationHome(this.getClass()).getDir().getParentFile().getParentFile().getAbsolutePath();
        Map<String, String> map = new HashMap<>();
        map.put("pathPrefix", pathPrefix);
        map.put("src", "equipment");
        String fileName = uploadUtil.saveFile(file, map);
        JSONObject object = JSON.parseObject(equipStr);

        Equipment equipment = new Equipment();
        equipment.setName(object.getString("name"));
        equipment.setCount(object.getInteger("count"));

        System.out.println(fileName);
        equipment.setImgUrl("http://localhost:" + port + "/equipment/img/" + fileName);
        boolean result = equipService.save(equipment);
        if (result) {
            redisUtils.deleteRedisKeys("equipmentNames");
            redisUtils.deleteRedisKeys("equipmentPage");
            return Result.ok("添加成功");
        } else
            return Result.fail().message("添加失败了");
    }


}
